package cn.net.msg.cxf.webservice.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import cn.net.msg.cxf.webservice.IMemberWebService;
import cn.net.msg.model.PageView;
import cn.net.msg.model.ReturnBean;
import cn.net.msg.model.ReturnPointBean;
import cn.net.msg.model.TbFavourite;
import cn.net.msg.model.TbUser;
import cn.net.msg.service.MemberService;
import cn.net.msg.service.base.Order;
import cn.net.msg.utils.FilePathUtils;
import cn.net.msg.utils.MD5;

import com.sina.sae.mail.SaeMail;

/**
 * <p>
 * FileName: MemberWebServiceImpl.java
 * </p>
 * <p>
 * Description: member的cxf服务实现类
 * <p>
 * Copyright: surepassserver(c) 2012
 * </p>
 * <p>
 * @author Vic Su
 * </p>
 * <p>
 * @content andyliu900@gmail.com
 * </p>
 * <p>
 * @version 1.0
 * </p>
 * <p>
 * CreatDate: 2012-12-6 下午10:25:49
 * </p>
 * <p>
 * Modification History
 */

@WebService
@SOAPBinding(style = Style.RPC)
@SuppressWarnings("deprecation")
public class MemberWebServiceImpl implements IMemberWebService {

    private static final long serialVersionUID = -7574227471498771234L;

    @Resource(name="memberService")
    MemberService service;

    @Override
    public ReturnBean loginUser(String LoginUserJSONObject) {
        // TODO Auto-generated method stub
        ReturnBean returnBean = new ReturnBean();  
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            TbUser tbUser = objectMapper.readValue(LoginUserJSONObject, TbUser.class);
            TbUser realTbUser = service.checkLogin(tbUser.getUserName(), tbUser.getUserPassword());
            if(realTbUser != null){ //存在记录，登录成功
                service.updateLoginTime(realTbUser);
                returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.true"));
                returnBean.setUserName(realTbUser.getUserName());
                returnBean.setUserId(realTbUser.getUserId());
            }else{
                returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
                returnBean.setUserName("");
                returnBean.setUserId(-1);
            }            
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnBean;
    }

    @Override
    public ReturnBean checkUser(@WebParam(name = "name")String name, @WebParam(name = "email")String email) {
        // TODO Auto-generated method stub
        ReturnBean returnBean = new ReturnBean();
        boolean nameFlag = service.isExsitName(name);
        boolean emailFlag = service.isExsitEmail(email);
        if(nameFlag || emailFlag){
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
        }else{          
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.true"));
        }
        return returnBean;
    }

    @Override
    public ReturnBean regUser(String RegUserJSONObject) {
        // TODO Auto-generated method stub
        ReturnBean returnBean = new ReturnBean();  

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            TbUser tbUser = objectMapper.readValue(RegUserJSONObject, TbUser.class);
            service.saveMember(tbUser);
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.true"));
            returnBean.setUserId(tbUser.getUserId());
        } catch (JsonParseException e) {
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
            e.printStackTrace();
        } catch (JsonMappingException e) {
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
            e.printStackTrace();
        } catch (IOException e) {
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
            e.printStackTrace();
        }
        return returnBean;
    }

    @Override
    public ReturnBean deleteUser(long id) {
        // TODO Auto-generated method stub
        ReturnBean returnBean = new ReturnBean();
        int num = service.deleteUser(id);
        if(num <= 0){
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
        }else{          
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.true"));
        }
        return returnBean;
    }

    @Override
    public ReturnBean updateUserInfo(String MemberJSONObject) {
        // TODO Auto-generated method stub
        ReturnBean returnBean = new ReturnBean();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            TbUser tbUser = objectMapper.readValue(MemberJSONObject, TbUser.class);
            TbUser oldTbUser = service.find(tbUser.getUserId());
            oldTbUser.setUserName(tbUser.getUserName() == null || "".equals(tbUser.getUserName())
                    ? oldTbUser.getUserName() : tbUser.getUserName());
            oldTbUser.setUserEmail(tbUser.getUserEmail() == null || "".equals(tbUser.getUserName()) 
                    ? oldTbUser.getUserEmail() : tbUser.getUserEmail());
            oldTbUser.setUserPassword(MD5.MD5Encode("").equals(tbUser.getUserPassword()) || tbUser.getUserPassword() == null
                    ? oldTbUser.getUserPassword() : tbUser.getUserPassword());
            oldTbUser.setUserSex(tbUser.getUserSex() == null || "".equals(tbUser.getUserSex())
                    ? oldTbUser.getUserSex() : tbUser.getUserSex());
            oldTbUser.setUserProvinceId(tbUser.getUserProvinceId() == -1
                    ? oldTbUser.getUserProvinceId() : tbUser.getUserProvinceId());
            oldTbUser.setUserCityId(tbUser.getUserCityId() == -1
                    ? oldTbUser.getUserCityId() : tbUser.getUserCityId());
            oldTbUser.setUserSummary(tbUser.getUserSummary() == null || "".equals(tbUser.getUserSummary())
                    ? oldTbUser.getUserSummary() : tbUser.getUserSummary());
            oldTbUser.setUserBirthday(tbUser.getUserBirthday() == null
                    ? oldTbUser.getUserBirthday() : tbUser.getUserBirthday());
            oldTbUser.setUserQQ(tbUser.getUserQQ() == null || "".equals(tbUser.getUserQQ())
                    ? oldTbUser.getUserQQ() : tbUser.getUserQQ());
            oldTbUser.setUserEdittime(new Date());
            oldTbUser.setTaskType(tbUser.getTaskType());

            service.update(oldTbUser);
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.true"));
        } catch (JsonParseException e) {
            e.printStackTrace();
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
        } catch (JsonMappingException e) {
            e.printStackTrace();
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
        } catch (IOException e) {
            e.printStackTrace();
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
        }

        return returnBean;
    }

    @Override
    public TbUser getUserInfo(long loginUserId) {
        // TODO Auto-generated method stub
        TbUser tbUser = service.find(loginUserId);
        if (tbUser != null) {
            tbUser.setUserSex(tbUser.getUserSex() == null ? "" : tbUser.getUserSex());
            tbUser.setUserProvinceId(tbUser.getUserProvinceId() == -1 ? -1 : tbUser.getUserProvinceId());
            tbUser.setUserCityId(tbUser.getUserCityId() == -1 ? -1 : tbUser.getUserCityId());
            tbUser.setUserSummary(tbUser.getUserSummary() == null ? "" : tbUser.getUserSummary());
            tbUser.setUserQQ(tbUser.getUserQQ() == null ? "" : tbUser.getUserQQ());    
        } else {
            tbUser = new TbUser();
        }
        return tbUser;
    }

    @Override
    public void uploadUserPoints(String userListJsonObject) {
        // TODO Auto-generated method stub
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<LinkedHashMap<String, Object>> userList = objectMapper.readValue(userListJsonObject, List.class);
            System.out.println(userList.size());
            for (int i = 0; i < userList.size(); i++) {
                Map<String, Object> map = userList.get(i);
                service.uploadUserPoints(map);
            }
        }catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ReturnPointBean getUserPoint(long userid) {
        // TODO Auto-generated method stub
        ReturnPointBean returnPointBean = service.getUserPoint(userid);
        return returnPointBean;
    }

    @Override
    public ReturnBean sendForgetpasswordEmail(String email) {
        // TODO Auto-generated method stub
        System.out.println("发过来的email:" + email);
        //这个类主要是设置邮件  
        //        MailSenderInfo mailInfo = new MailSenderInfo();   
        //        mailInfo.setMailServerHost(FilePathUtils.readValue("sendmail.server.smtphost"));   
        //        mailInfo.setMailServerPort(FilePathUtils.readValue("sendmail.server.smtpport"));   
        //        mailInfo.setValidate(true);   
        //        mailInfo.setUserName(FilePathUtils.readValue("sendmail.server.username"));   
        //        mailInfo.setPassword(FilePathUtils.readValue("sendmail.server.password"));   
        //        mailInfo.setFromAddress(FilePathUtils.readValue("sendmail.server.fromaddress"));   
        //        mailInfo.setToAddress(email);  
        //        String subject = FilePathUtils.readValue("sendmail.server.resetpassword.title");
        //        mailInfo.setSubject(subject);
        //        String content = FilePathUtils.readValue("sendmail.server.resetpassword.link");
        //        mailInfo.setContent(content);
        //
        //        //这个类主要来发送邮件 
        //        SimpleMailSender sms = new SimpleMailSender();  
        //        //        sms.sendTextMail(mailInfo);//发送文体格式   
        //        boolean isOk = sms.sendHtmlMail(mailInfo);//发送html格式 



        //        Properties p = new Properties();
        //        p.put("mail.smtp.host", FilePathUtils.readValue("sendmail.server.smtphost"));
        //        p.put("mail.smtp.port", FilePathUtils.readValue("sendmail.server.smtpport"));
        //        p.put("mail.smtp.auth", "true");
        //        Authenticator authenticator = new Authenticator() {
        //            @Override
        //            protected PasswordAuthentication getPasswordAuthentication() {
        //                return new PasswordAuthentication(FilePathUtils.readValue("sendmail.server.username"),FilePathUtils.readValue("sendmail.server.password"));
        //            }
        //        };
        //
        //        try {
        //            Session sendMailSession = Session.getDefaultInstance(p,authenticator);
        //            Message mailMessage = new MimeMessage(sendMailSession);
        //            Address from = new InternetAddress(FilePathUtils.readValue("sendmail.server.fromaddress"));
        //            mailMessage.setFrom(from);
        //            Address to = new InternetAddress(email);//设置接收人员
        //            mailMessage.setRecipient(Message.RecipientType.TO, to);
        //            mailMessage.setSubject(FilePathUtils.readValue("sendmail.server.resetpassword.title"));//设置邮件标题
        //            mailMessage.setText(FilePathUtils.readValue("sendmail.server.resetpassword.link")); //设置邮件内容
        //            // 发送邮件
        //            Transport.send(mailMessage);
        //        } catch (AddressException e) {
        //            // TODO Auto-generated catch block
        //            e.printStackTrace();
        //        } catch (MessagingException e) {
        //            // TODO Auto-generated catch block
        //            e.printStackTrace();
        //        }

        SaeMail mail = new SaeMail();
        //快速发送邮件
        //mail.quickSend("from@sina.com",new String[]{"to@sina.cn"},"邮件标题","邮件内容","smtpaccount@gmail.com","password");
        //mail.clean();//重用此对象 再次发送
        mail.setFrom(FilePathUtils.readValue("sendmail.server.fromaddress"));
        mail.setSmtpUsername(FilePathUtils.readValue("sendmail.server.fromaddress"));
        mail.setSmtpPassword(FilePathUtils.readValue("sendmail.server.password"));
        //        mail.setCc(new String[] { "cc@sina.cn" });//抄送地址
        mail.setTo(new String[] { email });//接收地址
        mail.setSubject(FilePathUtils.readValue("sendmail.server.resetpassword.title"));
        mail.setContentType("HTML");//邮件内容形式可选HTML/TEXT
        mail.setContent(FilePathUtils.readValue("sendmail.server.resetpassword.link"));
        //mail.setTls(true);//gmail需要设置此项 其他邮箱不需要
        mail.setCallbackUrl("callbackurl");//设置发送失败后回调的url
        boolean isOk = mail.send();//发送邮件

        ReturnBean returnBean = new ReturnBean();
        if(isOk){
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.true"));
        } else {
            //失败输出错误码和错误信息
            returnBean.setCode(FilePathUtils.readValue("cxfservice.return.code.false"));
            System.out.println(mail.getErrno());
            System.out.println(mail.getErrmsg());
        }
        return returnBean;
    }

    @Override
    public List<TbFavourite> getUserFavouriteForList(long userid, int maxresult,
            int currentpage) {
        List<TbFavourite> list = new ArrayList<TbFavourite>();
        PageView<TbFavourite> pageView = new PageView<TbFavourite>(maxresult, currentpage);  
        List<HashMap<String,Object>> queryParams = new ArrayList<HashMap<String,Object>>();
        HashMap map = new HashMap();
        map.put("opera", "eq");
        map.put("field", "favouritelistUserid");
        map.put("value", userid);
        queryParams.add(map);

        list = service.getUserFavouriteForList(pageView.getFirstResult(),pageView.getMaxresult(), queryParams,  Order.DESC,"favouritelistCreatdate");
        return list;
    }
}
